package com.katesoft.scale4j.rttp.jobs;

import com.hazelcast.core.IMap;
import com.hazelcast.core.IdGenerator;
import com.katesoft.scale4j.log.Logger;
import com.katesoft.scale4j.log.LogFactory;
import com.katesoft.scale4j.rttp.client.IClusterInstanceAware.ClusterInstanceAwareBean;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.JobParametersIncrementer;

import static com.katesoft.scale4j.rttp.internal.IRttpHazelcastRefs.JOB_PARAMS_INCREMENTER;

/**
 * this class will add unique run id for each job execution.
 *
 * @author kate2007
 */
public class DistributedJobParametersIncrementer extends ClusterInstanceAwareBean implements JobParametersIncrementer
{
    private final Logger logger = LogFactory.getLogger(getClass());

    @Override
    public JobParameters getNext(JobParameters parameters)
    {
        String jobName = parameters.getString(JobsUtility.JOB_NAME);
        long l = System.currentTimeMillis();
        if (getInstance().getLifecycleService().isRunning()) {
            IMap<Object, Object> map = getInstance().getMap(JOB_PARAMS_INCREMENTER);
            IdGenerator idGenerator = getInstance().getIdGenerator("rttp.jobs." + jobName);
            Object obj = map.get(jobName);
            l = idGenerator.newId();
            if (obj == null) {
                map.putIfAbsent(jobName, l);
            }
            else {
                map.replace(jobName, l);
            }
            logger.debug("added run.id=%s to job parameters", l);
        }
        return new JobParametersBuilder(parameters).addLong("run.id", l).toJobParameters();
    }
}
